<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加新闻-管理员</title>
<!-- <link rel="stylesheet" href="${BasePath}/css/bootstrap.min.css"> -->
<link href="https://cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="${BasePath}/css/bootstrap-pager.css">
<link rel="stylesheet" href="${BasePath}/css/bootstrap-switch.min.css">
<link rel="stylesheet" href="${BasePath}/css/common.css?v=${cssVersion}">
<script type="text/javascript" src="${BasePath}/js/ajaxHeader.js?v=${jsVersion}"></script>
<style>
.float{    
    float:left;    
    width : 200px;    
    height: 200px;    
    overflow: hidden;    
    border: 1px solid #CCCCCC;    
    border-radius: 10px;    
    padding: 5px;    
    margin: 5px;    
}    
img{    
    position: relative;    
}    
.result{    
    width: 200px;    
    height: 200px;    
    text-align: center;    
    box-sizing: border-box;    
}   

#file_input{  
    display: none;  
}  

.delete{  
    width: 200px;  
    height:200px;  
    position: absolute;  
    text-align: center;  
    line-height: 200px;  
    z-index: 10;  
    font-size: 30px;  
    background-color: rgba(255,255,255,0.8);  
    color: #777;  
    opacity: 0;  
    transition-duration: :0.7s;  
    -webkit-transition-duration: 0.7s;   
}  

.delete:hover{  
    cursor: pointer;  
    opacity: 1;  
} 
</style>
</head>
<body>
	<div class="panel panel-default">
	    <div class="panel-heading">
	        <div class="row" >
	        	<div class="col-lg-8">
		        	<strong>新闻添加（管理员端）</strong>
		        </div>
	        </div>
	    </div>
	    <div class="panel-body">
	        <div role="form">
				<div class="form-group">
					<label>新闻标题</label>
					<input type="text" class="form-control" id="title" placeholder="标题...">
				</div>
				<div class="form-group">
					<label>新闻内容</label>
					<textarea class="form-control" id="content" placeholder="内容..."  rows="5"></textarea>
				</div>
				<div class="form-group">
					<label>新闻图片</label>
	                <button id="add">添加图片</button>  
	                <input type="file" id="file_input" multiple accept="image/*"/>
	            </div> 
				<button class="btn btn-primary" data-loading-text="拼命上传中..." id="submit">立即添加</button>
			</div>
	    </div>
	</div>

<!-- 	<script type="text/javascript" src="${BasePath}/js/jquery-3.3.1.min.js"></script> -->
	<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
	<script type="text/javascript" src="${BasePath}/js/bootstrap.min.js"></script>
	<script type="text/javascript">
	$(document).ready(function(){
	    var input = document.getElementById("file_input");    
	    var result;    
	    var dataArr = []; // 储存所选图片的结果(文件名和base64数据)  
	    var fd;  //FormData方式发送请求    
	    var oAdd = document.getElementById("add");  
	    var oSubmit = document.getElementById("submit");  
	    var oInput = document.getElementById("file_input");  
	     
	    if(typeof FileReader==='undefined'){    
	        alert("抱歉，你的浏览器不支持 FileReader");    
	        input.setAttribute('disabled','disabled');    
	    }else{    
	        input.addEventListener('change',readFile,false);    
	    }　　　　　//handler    
	    
	        
	    function readFile(){
	        fd = new FormData();    
	        var iLen = this.files.length;  
	        var index = 0;  
	        for(var i=0;i<iLen;i++){  
	            if (!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)){　　//判断上传文件格式    
	                return alert("上传的图片格式不正确，请重新选择");    
	            }  
	            var reader = new FileReader();  
	            reader.index = i;    
	            fd.append(i,this.files[i]);  
	            reader.readAsDataURL(this.files[i]);  //转成base64    
	            reader.fileName = this.files[i].name;  
	  
	  
	            reader.onload = function(e){   
	                var imgMsg = {    
	                    name : this.fileName,//获取文件名    
	                    base64 : this.result   //reader.readAsDataURL方法执行完后，base64数据储存在reader.result里    
	                }   
	                dataArr.push(imgMsg);    
	                result = '<div class="delete"><strong>删除</strong></div><div class="result"><img src="'+this.result+'" alt=""/></div>';    
	                var div = document.createElement('div');  
	                div.innerHTML = result;    
	                div['className'] = 'float';  
	                div['index'] = index;    
	                document.getElementsByTagName('body')[0].appendChild(div);  　　//插入dom树    
	                var img = div.getElementsByTagName('img')[0];  
	                img.onload = function(){    
	                    var nowHeight = ReSizePic(this); //设置图片大小    
	                    this.parentNode.style.display = 'block';    
	                    var oParent = this.parentNode;    
	                    if(nowHeight){    
	                        oParent.style.paddingTop = (oParent.offsetHeight - nowHeight)/2 + 'px';    
	                    }    
	                }   
	  
	  
	                div.onclick = function(){  
	                    this.remove();                  // 在页面中删除该图片元素  
	                    delete dataArr[this.index];  // 删除dataArr对应的数据  
	                      
	                }  
	                index++;  
	            }    
	        }    
	    }    
	        
	    function addNews(){
	    	var $btn = $(this);
	    	var formData = new FormData();
			
	        formData.append("title", $("#title").val());
	        formData.append("content", $("#content").val());
// 	        formData.append("files",$("#file_input")[0].files);
	        
	        alert('添加新闻')
	        $.ajax({
	            url : "${BasePath}/page/admin/addNews", 
	            type : 'POST', 
	            data : formData, 
	            processData : false, // 告诉jQuery不要去处理发送的数据
	            contentType : false, // 告诉jQuery不要去设置Content-Type请求头
	            beforeSend:function(){
	            	$btn.button('loading');
	            },
	            success: function(data) {
	            	$btn.button('reset');
	            	console.log(data);
	            	if(data.result){
	            		alert("上传成功！");
	            		location.href = "${BasePath}/page/admin/news/list";
	            	}
	            	else{
	            		alert("上传失败！");
	            	}
	            }, 
	            error : function(err) { 
	            	$btn.button('reset');
	                var errMsg = "上传出错，详情：" + SON.stringify(err);
	                console.log(errMsg);
	                alert(errMsg);
	            } 
	        });
	    } 
	    
	    function send(){   
	        var submitArr = [];  
	        for (var i = 0; i < dataArr.length; i++) {  
	            if (dataArr[i]) {  
	                submitArr.push(dataArr[i]);  
	            }  
	        }  
	        // console.log('提交的数据：'+JSON.stringify(submitArr)) 
	        $.ajax({    
	            url : 'http://123.206.89.242:9999',    
	            type : 'post', 
	            data : JSON.stringify(submitArr),    
	            dataType: 'json',    
	            //processData: false,   用FormData传fd时需有这两项    
	            //contentType: false,    
	            success : function(data){    
	                console.log('返回的数据：'+JSON.stringify(data))    
	          　}
	 
	        })    
	    }    
	  
	    oAdd.onclick=function(){  
	        oInput.value = "";   // 先将oInput值清空，否则选择图片与上次相同时change事件不会触发  
	        oInput.click();   
	    }   
	  
	  
	    oSubmit.onclick=function(){    
	        /* if(!dataArr.length){    
	            return alert('请先选择文件');    
	        } */
// 	        send();
	        addNews();
	    }    
	});
	/*    
	 用ajax发送fd参数时要告诉jQuery不要去处理发送的数据，    
	 不要去设置Content-Type请求头才可以发送成功，否则会报“Illegal invocation”的错误，    
	 也就是非法调用，所以要加上“processData: false,contentType: false,”    
	 * */    
	    
	                
	function ReSizePic(ThisPic) {    
	    var RePicWidth = 200; //这里修改为您想显示的宽度值    
	    
	    var TrueWidth = ThisPic.width; //图片实际宽度    
	    var TrueHeight = ThisPic.height; //图片实际高度    
	        
	    if(TrueWidth>TrueHeight){    
	        //宽大于高    
	        var reWidth = RePicWidth;    
	        ThisPic.width = reWidth;    
	        //垂直居中    
	        var nowHeight = TrueHeight * (reWidth/TrueWidth);    
	        return nowHeight;  //将图片修改后的高度返回，供垂直居中用    
	    }else{    
	        //宽小于高    
	        var reHeight = RePicWidth;    
	        ThisPic.height = reHeight;    
	    }    
	}
	</script>
</body>
</html>